<template>
    <div class="info-collect">
        <Crumb name="Sparepart Database"></Crumb>

        <div class="content">
            <el-button
                    type="primary"
                    @click="openAdd"
            >Add New Sparepart
            </el-button>
            <label for="file" >Inventory</label>
            <input type="file" id="file" style="display: none" ref="file" @change="fileChange">
            <Search>
                <el-input
                        v-model="key"
                        size="small"
                        class="input"
                        placeholder="Search By part No"
                        prefix-icon="el-icon-search"
                > </el-input>
                <el-input
                        v-model="key1"
                        size="small"
                        class="input"
                        placeholder="Search By part Name"
                        prefix-icon="el-icon-search"
                > </el-input>
                <el-button
                        size="small"
                        type="primary"
                > Search
                </el-button>
            </Search>
            <div class="table-wrapper">
                <el-table
                        :data="partLists.slice((pageNum-1)*pageSize,pageNum*pageSize)"
                        border
                        row-key="id"
                        stripe
                        @filter-change="handleFilterChange"
                        style="width: 100%">
                    <el-table-column type="expand" label="total" width="80">
                        <template slot-scope="part">
                            <div><part-detail :partDetail="part.row"></part-detail></div>
                        </template>
                    </el-table-column>
                    <el-table-column
                            prop="partsNumber"
                            label="Part No"
                            width="180"
                    >
                    </el-table-column>
                    <el-table-column
                            prop="denomination"
                            label="Description"
                           >
                    </el-table-column>
                    <el-table-column
                            prop="designation"
                            label="Description"
                            >
                    </el-table-column>
                    <el-table-column
                            prop="systemName"
                            :filters="uniSystem"
                            label="System"
                    >
                    </el-table-column>
                    <el-table-column
                            prop="hostNumber"
                            :filters="uniUnit"
                            label="For Unit"
                    >
                    </el-table-column>
                    <el-table-column
                            prop="quantity"
                            label="Stock"
                    >
                    </el-table-column>
                    <el-table-column
                     prop="salePrice"
                     label="Sale Price"
                     >
                        <template slot-scope="part">
                            {{part.row.salePrice | money}}
                        </template>
                    </el-table-column>
                    <el-table-column label="Opr" width="250">
                        <template slot-scope="scope">
                            <el-button
                                    size="mini"
                                    @click="openEdit(scope.row)">Modify
                            </el-button>
                            <!--<el-button-->
                                    <!--size="mini"-->
                                    <!--type="warning"-->
                                    <!--@click="openStock(scope.row)">Stock Record-->
                            <!--</el-button>-->
                        </template>
                    </el-table-column>
                </el-table>
                <div class="page">
                    <el-pagination background
                                   :page-size="pageSize"
                                   @current-change="changePage"
                                   layout="prev, pager, next"
                                   :total="total"> </el-pagination>
                </div>
            </div>
            <div class="modal-wrapper">
                <el-dialog
                        title="Sparepart Database"
                        top="10"
                        :visible.sync="dialogVisible"
                        width="80%"
                        >

                    <el-form :model="ruleForm"  ref="ruleForm" label-width="200px" class="demo-ruleForm">
                        <el-form-item label="Product Brand" prop="brand">
                            <el-input v-model="ruleForm.brand"></el-input>
                        </el-form-item>
                        <el-form-item label="Part No" prop="partsNumber">
                            <el-input v-model="ruleForm.partsNumber"></el-input>
                        </el-form-item>
                        <el-form-item label="Description" prop="designation">
                            <el-input v-model="ruleForm.designation"></el-input>
                        </el-form-item>
                        <el-form-item label="Description" prop="denomination">
                            <el-input v-model="ruleForm.denomination"></el-input>
                        </el-form-item>
                        <el-form-item label="Unit Model" prop="hostNumber">
                            <el-input v-model="ruleForm.hostNumber"></el-input>
                        </el-form-item>
                        <el-form-item label="System" prop="systemName">
                            <el-input v-model="ruleForm.systemName"></el-input>
                        </el-form-item>
                        <el-form-item label="Sale Price" prop="salePrice">
                            <el-input v-model="ruleForm.salePrice"></el-input>
                        </el-form-item>
                        <el-form-item label="Purchase Price" prop="purchasePrice">
                            <el-input v-model="ruleForm.purchasePrice"></el-input>
                        </el-form-item>
                        <el-form-item label="Size" prop="size">
                            <el-input v-model="ruleForm.size"></el-input>
                        </el-form-item>
                        <el-form-item label="Weight" prop="weight">
                            <el-input v-model="ruleForm.weight"></el-input>
                        </el-form-item>
                        <el-form-item label="Instruction" prop="instruction">
                            <el-input v-model="ruleForm.instruction"></el-input>
                        </el-form-item>
                        <el-form-item label="Image">
                            <el-upload
                                    :on-success="successLoad"
                                    :on-remove="removeImage"
                                    class="upload-demo"
                                    list-type="picture"
                                    :file-list="imageList"
                                    drag
                                    name="upload_file"
                                    :action="url"
                                    multiple>
                                <i class="el-icon-upload"></i>
                                <div class="el-upload__text">Drag here，or <em>Click to upload</em></div>
                            </el-upload>
                        </el-form-item>
                    </el-form>
                    <span slot="footer" class="dialog-footer">
                        <el-button @click="dialogVisible = false">Cancel</el-button>
                        <el-button type="primary" @click="submitForm">Confirm</el-button>
                    </span>
                </el-dialog>
                <el-dialog :visible.sync="stockVisible" title="Stock" width="50%">
                    <part-stock-detail :partStockInList="partStockInList" :partStockOutList="partStockOutList"/>
                    <span slot="footer" class="dialog-footer">
                        <el-button @click="stockVisible = false">Cancel</el-button>
                    </span>
                </el-dialog>
                <el-dialog
                        title="Different Storage"
                        :visible.sync="showDifferent"
                        width="100%"
                        top="0"
                        >
                    <el-table
                            :data="differentList"
                            max-height="500"
                            style="width: 100%">
                        <el-table-column
                                prop="partsNum"
                                label="Parts Number"
                                width="180">
                        </el-table-column>
                        <el-table-column
                                prop="denomination"
                                label="Parts Name"
                                width="180">
                        </el-table-column>
                        <el-table-column
                                prop="designation"
                                label="Parts Name"
                                width="180">
                        </el-table-column>
                        <el-table-column
                                prop="statisticalQuantity"
                                label="Excel quantity"
                                width="180">
                        </el-table-column>
                        <el-table-column
                                prop="systemQuantity"
                                label="System quantity"
                                width="180">
                        </el-table-column>

                    </el-table>
                    <h4>Not Exist</h4>
                    <el-table
                            :data="notExistList"
                            max-height="500"
                            style="width: 100%;margin-top: 20px;">
                        <el-table-column
                                prop="partsNum"
                                label="Parts Number"
                                width="180">
                        </el-table-column>
                        <el-table-column
                                prop="denomination"
                                label="Parts Name"
                                width="180">
                        </el-table-column>
                        <el-table-column
                                prop="designation"
                                label="Parts Name"
                                width="180">
                        </el-table-column>
                        <el-table-column
                                prop="statisticalQuantity"
                                label="Excel quantity"
                                width="180">
                        </el-table-column>
                        <el-table-column
                                prop="systemQuantity"
                                label="System quantity"
                                width="180">
                        </el-table-column>

                    </el-table>
                    <span slot="footer" class="dialog-footer">
                    <el-button @click="showDifferent = false">ok</el-button>
                  </span>
                </el-dialog>

            </div>
        </div>
    </div>
</template>

<script>
    import Crumb from '@/components/common/crumb'
    import Search from '@/components/common/search'
    import partStockDetail from '@/components/part/partStockDetail'
    import partDetail from '../../components/part/partDetail'
    import {getPartDetail, modifyPart, addPart, getPartStockDetail, checkInventory,getUniSystem,getUniUnit} from "../../api";
    import {mapActions,mapGetters,mapMutations} from 'vuex';
    import {ERROR_OK} from "../../util/config";
    import mixins from '../../util/mixins'
    import {baseURL} from "../../util";

    export default {
        name: "part-list",
        mixins: [mixins],
        data() {
            return {
                uniSystem:[],
                uniUnit:[],
                imageList: [],
                partStockInList: [],
                partStockOutList: [],
                part: [],
                ruleForm: {},
                rules: {},
                filterOption:[],
                url: baseURL + '/file/uploadFileCDN',
                key: '',
                key1: '',
                dialogVisible: false,
                stockVisible: false,
                differentList:[],
                notExistList:[],
                showDifferent:false,
                stock: {
                    partId: '',
                    quantity: ''
                }
            }
        },
        created() {
            this.getPartLists();
            this.getUniUnit();
            this.getUniSystem();
        },
        filters: {
            money(num) {
                return num && num.toString()
                    .replace(/^\d+/g, (m) => m.replace(/(?=(?!^)(\d{3})+$)/g, ','))
            }
        },
        mounted() {
            this.total = this.partLists.length
        },
        computed: {
            ...mapGetters(['partList']),
            partLists: {
                get:function () {
                       if(this.filterOption.length) {
                           return this.partList.filter(item=>{
                               return this.filterOption.some(value=>{
                                   return (item.systemName && item.systemName.indexOf(value)>-1 ) || (item.hostNumber && item.hostNumber.indexOf(value) > -1)
                               })
                           }).filter(item => item.partsNumber.indexOf(this.key) > -1).filter(item => {
                               return (item.denomination && item.denomination.toLowerCase().indexOf(this.key1) > -1) || (item.designation && item.designation.toLowerCase().indexOf(this.key1) > -1) })
                       } else {
                           return this.partList.filter(item => item.partsNumber.indexOf(this.key) > -1).filter(item => {
                               return (item.denomination && item.denomination.toLowerCase().indexOf(this.key1) > -1) || (item.designation && item.designation.toLowerCase().indexOf(this.key1) > -1) })
                       }
                }
            }
        },
        methods: {
            handleFilterChange(filter){
                Object.keys(filter).forEach((key)=>{
                    this.filterOption = filter[key]
                });
            },
            async getUniUnit(){
                const {status,data} = await getUniUnit();
                if(status === ERROR_OK) {

                    this.uniUnit = data.map(item=>{
                        return {
                            text:item,
                            value:item
                        }
                    });
                }
            },
            async getUniSystem(){
                const {status,data} = await getUniSystem();
                if(status === ERROR_OK) {
                    this.uniSystem =  data.map(item=>{
                        return {
                            text:item,
                            value:item
                        }
                    });
                }
            },
            async openStock(stock) {
                const {status, data} = await getPartStockDetail(stock.id);
                if (status === ERROR_OK) {
                    this.partStockInList = data.stockInDetail;
                    this.partStockOutList = data.stockOutDetail;
                    this.stockVisible = true
                } else {
                    this.$notify.error('Error,please retry')
                }

            },
            submitForm() {
                this.$refs.ruleForm.validate(async (valid) => {
                    if (valid) {
                        if (this.ruleForm.imageUrl) {
                            this.ruleForm.imageUrl = this.ruleForm.imageUrl.join(',')
                        } else {
                            delete this.ruleForm.imageUrl
                        }
                        if (this.ruleForm.id) {
                            delete this.ruleForm.createTime;
                            delete this.ruleForm.updateTime;
                            let {status} = await modifyPart(this.ruleForm);
                            if (status === 0) {
                                this.ruleForm.totalPrice = this.ruleForm.quantity * this.ruleForm.salePrice
                                this.modPart(this.ruleForm);
                                this.$message({
                                    message: 'Modify Successfully',
                                    type: 'success'
                                });
                                this.dialogVisible = false
                            }
                        } else {
                            let {status, data} = await addPart(this.ruleForm);
                            if (status === 0) {
                                this.ruleForm.id = data.id;
                                this.ruleForm.totalPrice = this.ruleForm.quantity * this.ruleForm.salePrice;
                                this.addPart(this.ruleForm);
                                this.$message({
                                    message: 'Add Successfully',
                                    type: 'success'
                                });
                                this.dialogVisible = false
                            }
                        }
                    } else {
                        return false;
                    }
                });
            },
            successLoad(res) {
                if (this.ruleForm.imageUrl) {
                    this.ruleForm.imageUrl = this.ruleForm.imageUrl.concat(res.file_path)
                } else {
                    this.ruleForm.imageUrl = res.file_path
                }
            },
            removeImage(file) {
                if (this.ruleForm.imageUrl) {
                    const index = this.ruleForm.imageUrl.findIndex(img => {
                        return !img || img.url === file.url
                    });
                    this.ruleForm.imageUrl.splice(index, 1)
                }
            },
            async fileChange(e){
                const files = e.target.files;
                const file = files[0];
                if(file) {
                    let formData = new FormData();
                    formData.append('exFiles',file);
                    const {status,data} = await checkInventory(formData);
                    if(status === ERROR_OK) {
                        this.differentList = data.data.differentInventory;
                        this.notExistList = data.data.notExistExcel
                        this.showDifferent = true
                    }
                    }else{
                        this.$notify.error()
                    }
                this.$nextTick(()=>{
                    this.$refs.file.value = ''
                })
            },
            clear() {
                this.ruleForm = {};
                this.imageList = [];
            },
            openAdd() {
                this.clear();
                this.dialogVisible = true
            },
            openEdit(r) {
                // this.ruleForm = r;
                this.getPartDetail(r.id);
                this.dialogVisible = true

            },

            async getPartDetail(id) {
                let {status, data} = await getPartDetail(id);
                if (status === ERROR_OK) {
                    this.ruleForm = data;
                    if (data.imageUrl) {
                        this.imageList = data.imageUrl.map(item => {
                            return {
                                name: item,
                                url: item
                            }
                        })
                    } else {
                        this.imageList = []
                    }
                }
            },
            ...mapActions(['getPartLists', 'modPart']),
            ...mapMutations(['modQuantity', 'addPart'])
        },
        watch: {
            partLists(p) {
                this.total = p.length
            }
        },
        components: {
            Crumb, Search, partStockDetail,partDetail
        }
    }
</script>

<style scoped lang="scss">
    .info-collect {
        background: #f6;
        label{
            display: inline-block;
            line-height: 40px;
            padding: 0 20px;
            border-radius: 3px;
            cursor: pointer;
            background: #409eff;
            height: 40px;
            color: white;
            text-align: center;
            font-size: 14px;
            margin-left: 20px;
            &:hover{
                background: #6495ed;
            }
        }
        .content {
            text-align: left;
            padding: 20px 0;
            .table-wrapper {
                margin-top: 20px;
            }
            .page {
                text-align: center;
                margin-top: 10px;
            }
        }
    }
</style>